/*
 * Copyright (C) 2011 bus.fm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.busfm.util;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Random;

import android.text.TextUtils;

/**
 * <p>
 * Title:Utilities
 * </p>
 * <p>
 * Description: Utilities
 * </p>
 * <p>
 * Copyright (c) 2011 www.bus.fm Inc. All rights reserved.
 * </p>
 * <p>
 * Company: bus.fm
 * </p>
 * 
 * 
 * @author jingguo0@gmail.com
 * 
 */
public class Utilities {

    /**
     * Converts seconds to string, format mm:ss e.g. 04:12
     * 
     * @param seconds
     * @return
     */
    public static String secondsToString(int seconds) {
        String s = "" + seconds / 60 + ":";
        int t = seconds % 60;
        s += t < 10 ? "0" + t : t;
        return s;
    }

    public static boolean isEmpty(String str) {
        if ((null == str) || ("".equals(str.trim()))) {
            return true;
        } else {
            return false;
        }
    }

    public static String getDownloadFileFormat(String str) {
        if (null != null && !"".equals(str)) {
            return str.substring(str.lastIndexOf(".") + 1);
        }
        return "";
    }

    /**
     * <p>
     * Get UTF8 bytes from a string
     * </p>
     * 
     * @param string
     *            String
     * @return UTF8 byte array, or null if failed to get UTF8 byte array
     */
    public static byte[] getUTF8Bytes(String string) {
        if (string == null)
            return new byte[0];

        try {
            return string.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            /*
             * If system doesn't support UTF-8, use another way
             */

            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                DataOutputStream dos = new DataOutputStream(bos);
                dos.writeUTF(string);
                byte[] jdata = bos.toByteArray();
                bos.close();
                dos.close();
                byte[] buff = new byte[jdata.length - 2];
                System.arraycopy(jdata, 2, buff, 0, buff.length);
                return buff;
            } catch (IOException ex) {
                return new byte[0];
            }
        }
    }

    /**
     * <p>
     * Get string in UTF-8 encoding
     * </p>
     * 
     * @param b
     *            byte array
     * @return string in utf-8 encoding, or empty if the byte array is not
     *         encoded with UTF-8
     */
    public static String getUTF8String(byte[] b) {
        if (b == null)
            return "";
        return getUTF8String(b, 0, b.length);
    }

    /**
     * <p>
     * Get string in UTF-8 encoding
     * </p>
     */
    public static String getUTF8String(byte[] b, int start, int length) {
        if (b == null) {
            return "";
        } else {
            try {
                return new String(b, start, length, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                return "";
            }
        }
    }

    public static int getInt(int radix, String value, int faultValue) {
        if (value == null) {
            return faultValue;
        }

        try {
            /*
             * Integer.parseInt("ffffffff", 16) will fail, have to use Long...,
             * -_-
             */
            return (int) Long.parseLong(value.trim(), radix);
        } catch (NumberFormatException e) {
            return faultValue;
        }
    }

    public static int getInt(int radix, String value) {
        return getInt(radix, value, 0);
    }

    public static int getInt(String value, int faultValue) {
        return getInt(10, value, faultValue);
    }

    public static float getFloat(String value) {
        if (value == null)
            return 0f;

        try {
            return Float.parseFloat(value.trim());
        } catch (NumberFormatException e) {
            return 0f;
        }
    }

    public static double getDouble(String value) {
        if (value == null)
            return 0.0;

        try {
            return Double.parseDouble(value.trim());
        } catch (NumberFormatException e) {
            return 0.0;
        }
    }

    public static boolean getBoolean(String value) {
        if (getInt(value) == 0) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * <p>
     * Parse int value from string
     * </p>
     * 
     * @param value
     *            string
     * @return int value
     */
    public static int getInt(String value) {
        return getInt(10, value);
    }

    public static long getLong(String value) {
        if (value == null)
            return 0L;

        try {
            return Long.parseLong(value.trim());
        } catch (NumberFormatException e) {
            return 0L;
        }
    }

    /**
     * 歌曲ID的base64编码，加上前4后3的随机字母/数字,去掉等号
     * 
     * @return
     */
    public static String getShareLinked(String uid) {
        if (TextUtils.isEmpty(uid)) {
            return "";
        }
        String code = Base64.encode(uid);

        return (random(4) + code + random(3)).replace("=", "");
    }

    public static String random(int length) {
        Random random1 = new Random();
        String mRandom = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456790abcdefghijklmnopqrstuvwxyz";
        String result = "";
        for (int i = 0; i < length; i++) {
            int random = random1.nextInt(55);
            result += mRandom.substring(random, random + 1);
        }
        return result;
    }
}
